angular.module('tools.controllers',[])
.controller("SearchController",["$scope","$http",function($scope,$http){
	if(!sessionStorage.getItem("username")){
		location.href = "/login/";
	}
	$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
	$scope.prefixes = ["SHARP","BESTVOEM"];
	$scope.prefix = $scope.prefixes[0];
	$scope.orderFields = ["client_ip","product_name","content_name","payment_status","order_time","expire_time",
		"order_trans_no"];
	$scope.orderTitles = ["用户IP","产品名称","订购节目名称","付费状态","订购时间","失效时间","订单号"];
	$scope.paymentMap = ["待支付","支付成功","支付失败"];
	$scope.setPrefix = function(prefix){
		$scope.prefix = prefix;
	}
	$scope.getFields = function(obj){
		var fields = [];
		for(var key in obj){
			fields.push(key);
		}
		return fields;
	}
	$scope.getItems = function(data,fields){
		var items = [];
		for(var key in data){
			var item = data[key];
			item.payment_status = $scope.paymentMap[item.payment_status];
			var values = [];
			for(var key in fields){
				values.push(item[fields[key]]);
			}
			
			items.push(values);
		}
		return items;
	}
	$scope.getExtraData = function(data, field, fields){
		var values = [];
		if(fields.indexOf(field)!=-1){
			fields.splice(fields.indexOf(field),1);
			values = data[field];			
		}
		return values;
	}
	$scope.search = function(tvId,userId){
		var postData = {};
		if(tvId){
			postData = {field: "tvid",value: $scope.prefix+"$"+tvId};
		}else if(userId){
			postData = {field: "user_account",value: userId};
		}else{
			return;
		}
		$http.post("/searchAll/",$.param(postData)).success(function(data) {
			$scope.fields = ["ip_address", "user_account","net_operator_code","update_time","open_time","subscriber_group_code",
				"tvid","order_monthly","order_ppv"];
			$scope.titles = ["用户IP", "用户ID","net_operator_code","更新时间","开户时间","subscriber_group_code","tvid"];
			$scope.isQueryFail = !data.length;
			if($scope.isQueryFail){
				return;
			}	
			var order_monthly = $scope.getExtraData(data[0],"order_monthly",$scope.fields);
			var order_ppv = $scope.getExtraData(data[0],"order_ppv",$scope.fields);

			$scope.isTableExists = data.length;
			$scope.isMonthlyExists = order_monthly.length;
			$scope.isPpvExists = order_ppv.length;
			$scope.isQueryFail = !data.length||
				(data.length==1&&!$scope.fields.length&&!$scope.isMonthlyExists&&!$scope.isPpvExists);

			$scope.items = $scope.getItems(data, $scope.fields);
			$scope.monthlyItems = $scope.getItems(order_monthly, $scope.orderFields);
			$scope.ppvItems = $scope.getItems(order_ppv, $scope.orderFields);
		});
	}
}])